package com.example.xunai.service.ai.impl;

import com.example.xunai.config.AiModelConfig;
import com.example.xunai.service.ai.ModelConfigService;
import com.example.xunai.service.ai.strategy.AiModelFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class ModelConfigServiceImpl implements ModelConfigService {

    private final AiModelConfig aiModelConfig;
    private final AiModelFactory aiModelFactory;

    @Override
    public List<Map<String, Object>> getSupportedModels() {
        log.info("ModelConfigService - 获取支持的模型列表");

        List<Map<String, Object>> models = new ArrayList<>();

        aiModelConfig.getModels().forEach((key, config) -> {
            Map<String, Object> modelInfo = new HashMap<>();
            modelInfo.put("code", key);
            modelInfo.put("name", config.getModelName());
            modelInfo.put("description", getModelDescription(key));
            modelInfo.put("enabled", aiModelFactory.getStrategy(key) != null);
            modelInfo.put("maxTokens", config.getMaxTokens());
            modelInfo.put("temperature", config.getTemperature());
            modelInfo.put("streaming", config.getStreaming());
            models.add(modelInfo);
        });

        return models;
    }

    @Override
    public Map<String, Object> getModelConfig(String modelType) {
        AiModelConfig.ModelConfig config = aiModelConfig.getModels().get(modelType);
        if (config == null) {
            return null;
        }

        Map<String, Object> configInfo = new HashMap<>();
        configInfo.put("modelName", config.getModelName());
        configInfo.put("apiKey", maskApiKey(config.getApiKey()));
        configInfo.put("apiUrl", config.getApiUrl());
        configInfo.put("maxTokens", config.getMaxTokens());
        configInfo.put("temperature", config.getTemperature());
        configInfo.put("streaming", config.getStreaming());
        configInfo.put("valid", config.isValid());

        return configInfo;
    }

    @Override
    public boolean isModelAvailable(String modelType) {
        return aiModelFactory.getStrategy(modelType) != null &&
                aiModelConfig.getModels().containsKey(modelType);
    }

    @Override
    public boolean isModelConfigured(String modelType) {
        AiModelConfig.ModelConfig config = aiModelConfig.getModels().get(modelType);
        return config != null && config.isValid();
    }

    @Override
    public List<String> getConfiguredModelTypes() {
        return new ArrayList<>(aiModelConfig.getModels().keySet());
    }

    @Override
    public String getDefaultModel() {
        return aiModelConfig.getDefaultModel();
    }

    @Override
    public Map<String, Object> getConfigSummary() {
        Map<String, Object> summary = new HashMap<>();
        summary.put("defaultModel", aiModelConfig.getDefaultModel());
        summary.put("totalModels", aiModelConfig.getModels().size());

        List<Map<String, Object>> modelDetails = new ArrayList<>();
        aiModelConfig.getModels().forEach((key, config) -> {
            Map<String, Object> detail = new HashMap<>();
            detail.put("modelType", key);
            detail.put("modelName", config.getModelName());
            detail.put("apiUrl", config.getApiUrl());
            detail.put("streaming", config.getStreaming());
            detail.put("valid", config.isValid());
            detail.put("available", isModelAvailable(key));
            modelDetails.add(detail);
        });

        summary.put("models", modelDetails);
        return summary;
    }

    @Override
    public Map<String, Object> modelHealthCheck() {
        Map<String, Object> health = new HashMap<>();
        health.put("service", "ModelConfigService");
        health.put("status", "UP");
        health.put("supportedModels", getSupportedModels().size());
        health.put("defaultModel", getDefaultModel());
        health.put("timestamp", System.currentTimeMillis());

        // 检查各个模型的状态
        List<Map<String, Object>> modelStatus = new ArrayList<>();
        aiModelConfig.getModels().forEach((key, config) -> {
            Map<String, Object> status = new HashMap<>();
            status.put("model", key);
            status.put("available", isModelAvailable(key));
            status.put("strategyRegistered", aiModelFactory.getStrategy(key) != null);
            status.put("configured", config.isValid());
            modelStatus.add(status);
        });

        health.put("modelStatus", modelStatus);
        return health;
    }

    // ==================== 私有辅助方法 ====================

    private String getModelDescription(String modelType) {
        switch (modelType) {
            case "deepseek": return "DeepSeek AI 模型";
            case "baidu": return "百度文心一言模型";
            case "openai": return "OpenAI GPT 模型";
            case "claude": return "Claude 模型";
            case "spark": return "讯飞星火模型";
            case "qwen": return "通义千问模型";
            default: return "自定义模型";
        }
    }

    private String maskApiKey(String apiKey) {
        if (apiKey == null || apiKey.length() <= 8) {
            return "***";
        }
        return apiKey.substring(0, 4) + "***" + apiKey.substring(apiKey.length() - 4);
    }
}